package com.alex.cacheControl;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

public class CacheControlHeaderFilter implements Filter {

	private long expiresSeconds;

	public void destroy() {

	}

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse resp = (HttpServletResponse)res;
		resp.setDateHeader("Expires", System.currentTimeMillis() + expiresSeconds * 1000L);
		resp.setHeader("Cache-Control", "private,max-age=" + expiresSeconds);
		chain.doFilter(req,res);
	}

	public void init(FilterConfig cfg) throws ServletException {
		String expiresSecondsParam = cfg.getInitParameter("expiresSeconds");
		if (expiresSecondsParam != null)
			this.expiresSeconds = Long.valueOf(expiresSecondsParam).longValue();
		else
			this.expiresSeconds = 31536000L;
	}

}
